﻿using System.Windows;
using MugenMvvmToolkit.Interfaces;

namespace MugenMvvmToolkit
{
    /// <summary>
    ///     Represents the base class for Mvvm application.
    /// </summary>
    public abstract class MvvmApplication : Application
    {
        #region Fields

        private static IBootstrapper _bootstrapper;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="MvvmApplication" /> class.
        /// </summary>
        protected MvvmApplication()
        {
            _bootstrapper = null;
        }

        #endregion

        #region Overrides of Application

        /// <summary>
        ///     Raises the <see cref="E:System.Windows.Application.Startup" /> event.
        /// </summary>
        /// <param name="e">
        ///     A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            Bootstrapper = GetBootstrapper();
            if (!Bootstrapper.IsStarted)
                Bootstrapper.Start();
            base.OnStartup(e);
        }

        /// <summary>
        ///     Raises the <see cref="E:System.Windows.Application.Exit" /> event.
        /// </summary>
        /// <param name="e">
        ///     An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.
        /// </param>
        protected override void OnExit(ExitEventArgs e)
        {
            if (Bootstrapper != null)
                Bootstrapper.Stop();
            base.OnExit(e);
        }

        #endregion

        #region Properties

        /// <summary>
        ///     Gets the <see cref="IBootstrapper" /> for the current <see cref="MvvmApplication" />.
        /// </summary>
        public static IBootstrapper Bootstrapper
        {
            get { return _bootstrapper; }
            private set
            {
                Should.PropertyBeNotNull(value, "Bootstrapper");
                _bootstrapper = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        ///     Gets the <see cref="IBootstrapper" /> for the current <see cref="MvvmApplication" />.
        /// </summary>
        /// <returns>
        ///     An instance of <see cref="IBootstrapper" />.
        /// </returns>
        protected abstract IBootstrapper GetBootstrapper();

        #endregion
    }
}